package com.ruoyi.system.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.system.domain.AwMyPlan;
import com.ruoyi.system.domain.AwPlanDetail;
import com.ruoyi.system.enums.PlanStatusEnum;
import com.ruoyi.system.service.IAwMyPlanService;
import com.ruoyi.system.service.IAwPlanDetailService;
import com.ruoyi.system.timing.ScheduleTimingPool;
import com.ruoyi.system.timing.callback.impl.SchedulePlanCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : anxinr
 * @date : 2023/8/16 15:12
 */
@Slf4j
@Component
@EnableScheduling
public class MyPlanSchedule {

    @Autowired
    private IAwMyPlanService planService ;

    @Autowired
    private IAwPlanDetailService detailService ;

    @Autowired
    private SchedulePlanCallback planCallback ;

    public static final Integer WEEK_7 = 1 ;
    public static final Integer WEEK_6 = 7 ;


    /**
     * 开启计划任务池
     */
    @Scheduled(cron = "0 0 0 * * ? ")
    public void startMyPlan() {
        log.info("定时任务池，定时任务启动=====================================================");
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        int weekday = instance.get(Calendar.DAY_OF_WEEK);
        System.out.println("weekday = " + weekday);
        /**周一周三和周五执行*/
//        if (weekday != WEEK_7 && weekday != WEEK_6) {
            /**先关闭任务池再开启*/
            ScheduleTimingPool.closeTimingPool();
            resetMyPlanInfo() ;
            List<AwMyPlan> plans = this.planService.list();
            if (CollectionUtils.isEmpty(plans)) {
                return;
            }
            List<AwMyPlan> normalPlanList = plans.stream().
                    filter((p) -> (p.getStatus().equals(PlanStatusEnum.PLAN_STATUS_NORMAL.getCode()))).
                    filter(p -> p.getNoticeCount() > 0).
                    collect(Collectors.toList());
            if (CollectionUtils.isEmpty(normalPlanList)) {
                return;
            }
            for (AwMyPlan myPlan : normalPlanList) {
                LambdaUpdateWrapper<AwMyPlan> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(AwMyPlan::getId ,myPlan.getId()) ;
                wrapper.set(AwMyPlan::getNoticeCount ,myPlan.getNoticeCount() - 1) ;
                planService.update(wrapper) ;
            }
            log.info("开始每日任务计划，启动的计划为 -> {}", normalPlanList.stream().collect(Collectors.toMap(AwMyPlan::getName, AwMyPlan::getName)).values());
            LambdaQueryWrapper<AwPlanDetail> wrapper = new LambdaQueryWrapper<>();
            for (AwMyPlan plan : normalPlanList) {
                wrapper.eq(AwPlanDetail::getPlanId, plan.getId());
                List<AwPlanDetail> details = this.detailService.list(wrapper);
                /**如果没有详细计划则跳过*/
                if (CollectionUtils.isEmpty(details)) {
                    continue;
                }
                for (AwPlanDetail detail : details) {
                    ScheduleTimingPool.putTask(
                            detail,
                            detail.getScheduleDescribe(),
                            detail.getStartTime(),
                            detail.getEndTime(),
                            detail.getStatus(),
                            detail.getFrequency(),
                            planCallback
                    );
                }
                wrapper.clear();
            }
            ScheduleTimingPool.startTimingPool() ;
//        }
    }

    private void resetMyPlanInfo() {
        List<AwMyPlan> list = this.planService.list();
        LambdaUpdateWrapper<AwMyPlan> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(AwMyPlan::getStatus ,PlanStatusEnum.PLAN_STATUS_NORMAL.getCode()) ;
        wrapper.gt(AwMyPlan::getNoticeCount ,PlanStatusEnum.PLAN_STATUS_NORMAL.getCode()) ;
        planService.update(wrapper) ;
        LambdaUpdateWrapper<AwPlanDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(AwPlanDetail::getStatus ,PlanStatusEnum.PLAN_STATUS_NORMAL.getCode()) ;
        updateWrapper.in(AwPlanDetail::getPlanId , list.stream().collect(Collectors.toMap(AwMyPlan::getId ,AwMyPlan::getId)).values()) ;
        detailService.update(updateWrapper) ;
    }
}
